package data;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;

import database.ConnexionDB;

public class ModeleDynamiqueObjetAlerte extends AbstractTableModel implements Observer, TableModelListener{
	private Object[][] donnees;
	private final String[] entetes = {"Id","Type", "Label", "Chemin"};
	private ArrayList<Alerte> listAlertes = new ArrayList<Alerte>();
	private ConnexionDB DB;
	
	public ModeleDynamiqueObjetAlerte(ConnexionDB BD)
	{
		super();
		DB = BD;
		this.addTableModelListener(this);
	}
	public ConnexionDB getDB() {
		return DB;
	}
	public void setDB(ConnexionDB dB) {
		DB = dB;
	}
	public int getRowCount() {
        return listAlertes.size();
    }

    public int getColumnCount() {
        return entetes.length;
    }

    public String getColumnName(int columnIndex) {
        return entetes[columnIndex];
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        switch(columnIndex){
            case 0:
                return listAlertes.get(rowIndex).getIdAlerte();
            case 1:
                return listAlertes.get(rowIndex).getTypeAlerte();
            case 2:
                return listAlertes.get(rowIndex).getLabelAlerte();
            case 3:
                return listAlertes.get(rowIndex).getCheminAlerte();
            default:
                return null; 
        }
    }
    
    /*public boolean isCellEditable(int row, int column) {
        return true;
      }*/
    
    public void removeRow(int row) {
		listAlertes.remove(row);
		fireTableStructureChanged();
	}
    
    public void insertRow(int row, Alerte a) {
    	listAlertes.add(row, a);
		fireTableStructureChanged();
	}
    
    public void addRow(Alerte a) {
		addRow(a);
		fireTableStructureChanged();
	}

	public void addAlerte(Alerte alerte) {
		listAlertes.add(alerte);
        fireTableRowsInserted(listAlertes.size() -1, listAlertes.size() -1);
    }
	
	public void clear(){
		listAlertes.clear();
		fireTableStructureChanged();
	}
	@Override
	public void update(Observable arg0, Object arg1){
		// DataBase changed
		ConnexionDB DB = (ConnexionDB) arg0;
		String requeteSelectUsers = "SELECT * FROM alertes";
      	 
        ResultSet resultat; 
        clear();
        
        try {
			resultat = DB.executerRequete(requeteSelectUsers);
			while(resultat.next()){
	   			   Alerte a = new Alerte();
	               a.setIdAlerte(resultat.getInt("id_alerte"));
	               a.setTypeAlerte(resultat.getString("type_alerte"));
	               a.setLabelAlerte(resultat.getString("label_alerte"));
	               a.setCheminAlerte(resultat.getString("chemin_alerte"));
	               a.setTempAlerte(resultat.getLong("temp_alerte"));
	               a.setTypechrono(resultat.getInt("type_chrono"));
	               a.setListUtilisateur(DB.getUtilisateurs_alertes(a.getIdAlerte()));
	               addAlerte(a);
	           }
		} catch (SQLException e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}
	}
	public ArrayList<Alerte> getlistAlertes() {
		return listAlertes;
	}
	public void setlistAlertes(ArrayList<Alerte> listAlertes) {
		this.listAlertes = listAlertes;
	}
	
	public void setValueAt(Object value, int row, int col) 
	{	
		try {
			updateAlertes(value,row,col);
		} catch (SQLException e) {
			// Auto-generated catch block
			e.printStackTrace();
		}
    }
	
	public Thread insertLigneAlertes(final Alerte a1) throws SQLException
	{
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				//  Auto-generated method stub
				System.out.println("\n Type :" + a1.getTypeAlerte()+ "\n Label :" + a1.getLabelAlerte()+ "\n Chemin :" + a1.getCheminAlerte());
				try {
					getDB().insertLigneAlertes(a1.getTypeAlerte(), a1.getLabelAlerte(), a1.getCheminAlerte(),a1.getTempAlerte(),a1.getTypechrono());
				} catch (SQLException e) {
					// Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		t.start();
		return t;
	}
	
	public Thread deleteAlerte(final int id) throws SQLException
	{	
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				//  Auto-generated method stub
				try {
						System.out.println(id);
						getDB().deleteLigneAlertes(id);
				} catch (SQLException e) {
					// Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		t.start();
		return t;
	}
	
	public void updateAlertes(final Object value,final int row,final int col) throws SQLException
	{
		new Thread(new Runnable() {
			@Override
			public void run() {
				//  Auto-generated method stub
				try {
					int id = getlistAlertes().get(row).getIdAlerte();
					Alerte a = DB.selectAlerteId(id);
					System.out.println("Nom colonne " + getColumnName(col));
					if(getColumnName(col).equals("Type")) 
						DB.updateLigneAlertesType(id,value.toString());
					else if(getColumnName(col).equals("Label"))
						DB.updateLigneAlertesLabel(id,value.toString());
					else if(getColumnName(col).equals("Chemin"))
						DB.updateLigneAlertesChemin(id,value.toString());
				} catch (SQLException e) {
					//  Auto-generated catch block
					e.printStackTrace();
				}
			}

		}).start();
		
	}	
	
	@Override
	public void tableChanged(TableModelEvent arg0) {
		// Auto-generated method stub
		
	}
}
